package lium.lbs.lbsim.jgchat.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.LoginStateChangeEvent;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lmlibrary.Constants;
import com.lmlibrary.bean.ResponseBean;
import com.lmlibrary.exception.MyException;
import com.lmlibrary.utils.StatusBarUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.utils.OkLogger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import lium.lbs.lbsim.R;
import lium.lbs.lbsim.base.BaseParamMap;
import lium.lbs.lbsim.jgchat.utils.DialogCreator;
import lium.lbs.lbsim.jgchat.utils.FileHelper;
import lium.lbs.lbsim.jgchat.utils.SharePreferenceManager;
import lium.lbs.lbsim.jgchat.utils.swipeback.app.SwipeBackActivity;
import lium.lbs.lbsim.utils.SpUtils;
import lium.lbs.lbsim.utils.ToastUtils;
import okhttp3.Call;

import java.io.File;
import java.lang.reflect.Field;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

public class BaseActivity extends SwipeBackActivity {

    protected int mWidth;
    protected int mHeight;
    protected float mDensity;
    protected int mDensityDpi;
    private TextView mJmui_title_tv;
    private ImageButton mReturn_btn;
    private TextView mJmui_title_left;
    public Button mJmui_commit_btn;
    protected int mAvatarSize;
    protected float mRatio;
    private Dialog dialog;
    private int mColor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mybase);
        //注册sdk的event用于接收各种event事件
        JMessageClient.registerEventReceiver(this);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mDensity = dm.density;
        mDensityDpi = dm.densityDpi;
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
        mRatio = Math.min((float) mWidth / 720, (float) mHeight / 1280);
        mAvatarSize = (int) (50 * mDensity);


    }

    private void setBarColor() {
        // 设置默认的颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(), Color.TRANSPARENT); //改为透明   
            } catch (Exception e) {
            }
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//7.0透明状态栏    //透明状态栏    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);//完全隐藏状态栏    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);    }

    }


    //初始化各个activity的title
    public void initTitle(boolean returnBtn, boolean titleLeftDesc, String titleLeft, String title, boolean save, String desc) {
        mReturn_btn = (ImageButton) findViewById(R.id.return_btn);
        mJmui_title_left = (TextView) findViewById(R.id.jmui_title_left);
        mJmui_title_tv = (TextView) findViewById(R.id.jmui_title_tv);
        mJmui_commit_btn = (Button) findViewById(R.id.jmui_commit_btn);

        if (returnBtn) {
            mReturn_btn.setVisibility(View.VISIBLE);
            mReturn_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        if (titleLeftDesc) {
            mJmui_title_left.setVisibility(View.VISIBLE);
            mJmui_title_left.setText(titleLeft);
        }
        mJmui_title_tv.setText(title);
        if (save) {
            mJmui_commit_btn.setVisibility(View.VISIBLE);
            mJmui_commit_btn.setText(desc);
        }

    }

    public void displayImageFile(File file, ImageView imageView) {
        Glide.with(getApplicationContext()).load(file).into(imageView);
    }

    public void displayImageFile(File file, ImageView imageView, @DrawableRes int errorImage) {
        RequestOptions options = new RequestOptions();
        options.placeholder(errorImage);
        Glide.with(getApplicationContext()).load(file).apply(options).into(imageView);
    }

    public void displayImage(String url, ImageView imageView) {
        Glide.with(getApplicationContext())
                .load(url)
                .into(imageView);
    }

    public void displayImage(String url, @DrawableRes int errorImage, ImageView imageView) {
        RequestOptions options = new RequestOptions();
        options.placeholder(errorImage);
        Glide.with(getApplicationContext())
                .load(url)
                .apply(options)
                .into(imageView);
    }

    public <T> void handleError(Response<T> response) {
        if (response == null) return;
        if (response.getException() != null) response.getException().printStackTrace();
        int code = response.code();
        if (code == 404) {
            Log.d("JsonCallback", "404 当前链接不存在");
        }
        Throwable exception = response.getException();
        if (response.getException() instanceof SocketTimeoutException) {
            Log.d("JsonCallback", "请求超时");
        } else if (response.getException() instanceof SocketException) {
            Log.d("JsonCallback", "服务器异常");
        } else if (response.getException() instanceof MyException) { //个人自定义 异常 根据后台 约定值判断异常雷系
            switch (((MyException) response.getException()).getErrorBean().status) {
                case 1://约定的数据错误
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
                default:
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
            }

        }
    }

    public <T> void postData(String url, HashMap paramMap, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        String paramJson = new Gson().toJson(m);
        OkLogger.e("参数:" + paramJson);
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        postRequest.execute(callback);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    public void goToActivity(Context context, Class toActivity) {
        Intent intent = new Intent(context, toActivity);
        startActivity(intent);
        finish();
    }

    public void onEventMainThread(LoginStateChangeEvent event) {
        final LoginStateChangeEvent.Reason reason = event.getReason();
        UserInfo myInfo = event.getMyInfo();
        if (myInfo != null) {
            String path;
            File avatar = myInfo.getAvatarFile();
            if (avatar != null && avatar.exists()) {
                path = avatar.getAbsolutePath();
            } else {
                path = FileHelper.getUserAvatarPath(myInfo.getUserName());
            }
            SharePreferenceManager.setCachedUsername(myInfo.getUserName());
            SharePreferenceManager.setCachedAvatarPath(path);
            JMessageClient.logout();
        }
        switch (reason) {
            case user_logout:
                View.OnClickListener listener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.jmui_cancel_btn:
                                dialog.dismiss();
                                /*Intent intent = new Intent(BaseActivity.this, lium.lbs.lbsim.activity.LoginActivity.class);
                                startActivity(intent);*/

                                break;
                            case R.id.jmui_commit_btn:
                                dialog.dismiss();
                                JMessageClient.login(SpUtils.getInstance().get(Constants.memberId, "").toString(), "123456", new BasicCallback() {
                                    @Override
                                    public void gotResult(int responseCode, String responseMessage) {
                                        if (responseCode == 0) {
                                            Intent intent = new Intent(BaseActivity.this, lium.lbs.lbsim.activity.MainActivity.class);
                                            startActivity(intent);
                                        }
                                    }
                                });
                                dialog.dismiss();
                                break;
                        }
                    }
                };
                dialog = DialogCreator.createLogoutStatusDialog(BaseActivity.this, "您的账号在其他设备上登录", listener);
                dialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
                dialog.setCanceledOnTouchOutside(false);
                //dialog.show();
                break;
            case user_password_change:
                Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onDestroy() {
        //注销消息接收
        JMessageClient.unRegisterEventReceiver(this);
        if (dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
    }


}
